import { formatMessage } from 'umi-plugin-react/locale';
import { docLibraryDelete, docLibraryInfo, docLibraryUpdate } from "@/services/knowledgeFile";
import { Button, Select ,Card, Form, Icon, Input, Modal, Radio, Skeleton, Tabs, Upload, message } from "antd";
import React from "react";
import styles from './index.less'
import moment from "moment";
import { getUserAuthList } from "@/services/user";
import AuthUser from "./authUser";
import { selectDcTagList } from "@/services/knowledgeFile";
import { AuthUserList,TenantUserList } from "@/utils/CommonComponent";

class DocLibrarySetting extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      info:{},
      loading:false,
      activeKey:'base',
      examples:[
        'linear-gradient(to top right, #80CFF6, #5A5CC3)',
        'linear-gradient(to top right, #80D1F6, #5A9EBC)',
        'linear-gradient(to top right, #85CDF1, #DD5C6E)',
        'linear-gradient(to top right, #0270A0, #A3A8AA)',
        'linear-gradient(to top right, #046DA1, #7F03FB)',
        'linear-gradient(to top right, #80CFF6, #5ac39b)',
      ],
      imgUrl:"",
      currentCheck:"",
      authType:'0',
      search:"",
      isAdmin:false,
      isEmpty:false,
      list:[],
      tagList:[],
    }
  }

  componentDidMount(){
    this.getDetail()
    this.getTagList()
  }

  getTagList(){
    selectDcTagList().then(data=>{
      this.setState({tagList:data})
    })
  }
  getDetail = () => {
    const { location:{query,pathname},form:{setFieldsValue} } = this.props;
    const { examples,activeKey } = this.state;
    this.setState({
      loading:false,
      isAdmin:pathname.indexOf("publicResource") != -1
    },async () => {
      const res = await docLibraryInfo({id:query.docLibraryId})
      if(activeKey == 'base'){
        setFieldsValue({
          name:res.name,
          docLibraryIntroduction:res.libraryIntroduction,
          publicTime:res.publicTime,
          tenantName:res.tenantName,
          createTime:res.createTime,
          createUserName:res.createUserName,
          tags:res.tags
        })
      }
      this.setState({
        info:res,
        loading:false,
        currentCheck:res.libraryBackground ? res.libraryBackground : examples[0],
        imgUrl:res.libraryBackground && res.libraryBackground.indexOf("/download/minio") != -1 ? res.libraryBackground : ''
      })
    })
  }

  onChangeTab = activeKey => {
    this.setState({
      activeKey
    },() => {
      if(activeKey == 'member'){
        this.AuthUser.getList()
      }else if(activeKey == 'authorized'){
        this.TenantUserList.getList()
      }
    })
  }

  doSave = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        this.doSaveOk(values)
      }
    })
  }

  doSaveOk = async values => {
    const { info,currentCheck } = this.state;
    const res = await docLibraryUpdate({
      ...info,
      name:values.name,
      docLibraryIntroduction:values.docLibraryIntroduction,
      tags:values.tags,
      libraryBackground:currentCheck,
    })
    message.info(res.message)
    this.getDetail()
  }

  doSaveMember = async e => {
    const { info } = this.state;
    const res = await docLibraryUpdate({
      ...info,
      docLibraryIntroduction:info.libraryIntroduction,
      permissionType:e.target.value
    })
    message.info(res.message)
    this.getDetail() 
  }

  doSaveSafty = async (value,key) => {
    const { info } = this.state;
    const res = await docLibraryUpdate({
      ...info,
      docLibraryIntroduction:info.libraryIntroduction,
      [key]:value
    })
    message.info(res.message)
    this.getDetail() 
  }

  doDeleteConfirm = () => {
    const that = this;
    Modal.confirm({
      title:formatMessage({ id: 'knowledgeFile.docLibrarySetting.deleteTitle' }),
      content:formatMessage({ id: 'knowledgeFile.docLibrarySetting.deleteContent' }),
      okText:formatMessage({ id: 'knowledgeFile.docLibrarySetting.confirm' }),
      cancelText:formatMessage({ id: 'knowledgeFile.docLibrarySetting.cancel' }),
      okType:"danger",
      onOk(){
        that.doDelete()
      }
    })
  }

  doDelete = async () => {
    const { info } = this.state;
    const res = await docLibraryDelete({id:info.id})
    if(res.code == -1){

    }else{
      message.info(res.message)
      const { history } = this.props;
      history.push({ pathname: '/documentLibrary',query:{} })
    }
  }

  renderBg = bg => {
    if(bg){
      if(bg.indexOf("/download/minio") != -1){
        return {
          backgroundImage:`url(${bg})`,
          backgroundRepeat:"no-repeat",
          backgroundSize:"100% 100%"
        }
      }else{
        return {
          background:bg
        }
      }
    }else{
      return {
        background:"linear-gradient(to top right, #80CFF6, #5A5CC3)"
      }
    }
  }

  onChangeAuthType = authType => {
    this.setState({
      authType
    },() => {
      this.AuthUser.getList()
    })
  }

  doSearchByDocument = () => {
    this.AuthUser.doSearchByDocument(this.state.search)
  }

  render(){
    const { info,loading,activeKey,examples,imgUrl,currentCheck ,authType,search,isAdmin,isEmpty,list,tagList} = this.state;
    const { form:{getFieldDecorator},history,location:{query:{docLibraryId}} } = this.props;
    const that = this;
    const Uploadprops = {
      name: 'file',
      action:'/cloud/file/upload',
      showUploadList:false,
      beforeUpload(file){
        let b = /\.(png|jpg|gif)$/;
        let a = file.name.toLowerCase();
    
        const pig = b.test(a);
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;
    
        if (!pig) {
          if (!isLt2M) {
            message.error(formatMessage({ id: 'knowledgeFile.docLibrarySetting.uploadSizeLimit' }));
          } else {
            message.error(formatMessage({ id: 'knowledgeFile.docLibrarySetting.uploadImageFormat' }));
          }
        } else {
          if (!isLt2M) {
            message.error("请上传小于2M的图片");
          }
        };
        return isJPG && isLt2M && pig;
      },
      onChange(file) {
        if (file.file.status === "done") {
          that.setState({
            imgUrl: file.file.response.url,
            currentCheck:file.file.response.url
          });
        }
      },
      accept:'.png,.jpg'
    };
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px',
    };
    return (
      <Card loading={loading} style={{height:"100%"}}>
        <div style={{marginBottom:10,fontSize:16,fontWeight:500}}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.pageTitle' })}</div>
        <Tabs activeKey={activeKey} onChange={this.onChangeTab} tabBarExtraContent={<Button onClick={() => history.push({ pathname: isAdmin ? '/publicResource/documentLibrary' : '/documentLibrary',query:{} })}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.returnList' })}</Button>}>
          <Tabs.TabPane key="base" tab={formatMessage({ id: 'knowledgeFile.docLibrarySetting.basicInfo' })}>
            <Form style={{width:'70%'}}>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.name' })}>
                {getFieldDecorator("name",{rules:[{required:true,message:formatMessage({ id: 'knowledgeFile.docLibrarySetting.nameRequired' })}]})(
                  <Input disabled={isAdmin} />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.tags' })}>
                {getFieldDecorator("tags")(
                    <Select mode='multiple' disabled={isAdmin}>
                      {
                        tagList.map(item=>{
                          return <Select.Option value={item.id}>{item.tagName}</Select.Option>
                        })
                      }
                    </Select>
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.source' })}>
                {getFieldDecorator("tenantName")(
                  <Input disabled />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.creator' })}>
                {getFieldDecorator("createUserName")(
                    <Input disabled />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.publicTime' })}>
                {getFieldDecorator("publicTime")(
                  <Input disabled />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.createTime' })}>
                {getFieldDecorator("createTime")(
                  <Input disabled />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.introduction' })}>
                {getFieldDecorator("docLibraryIntroduction")(
                  <Input.TextArea autoSize={{ minRows: 6, maxRows: 15 }} disabled={isAdmin} />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'knowledgeFile.docLibrarySetting.cover' })}>
                <div className={styles.posterBox}>
                  <div className={styles.libraryContainer} style={{padding:0}}>
                    <div className={styles.gridItem}>
                      <div className={styles.gridBg} style={{background:currentCheck}}>
                        {info.permissionType == 1 ? <img src={currentCheck} /> : null}
                      </div>
                      <h3 className={styles.docName} style={{ WebkitBoxOrient: 'vertical' }}>{info.name}</h3>
                      <p className={styles.intro} title={info.libraryIntroduction} style={{ WebkitBoxOrient: 'vertical' }}>{info.libraryIntroduction}</p>
                      {info.permissionType == 1 ? <div className={styles.isShared}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.isPublic' })}</div> : ''}
                      
                    </div>
                  </div>

                  <div style={{width:'100%'}}>
                    <div className={styles.posterTop}>
                      <div>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.color' })}</div>
                      <Upload {...Uploadprops} disabled={isAdmin}>
                        <Button size="small" disabled={isAdmin}>
                          <Icon type="upload" />{formatMessage({ id: 'knowledgeFile.docLibrarySetting.upload' })}
                        </Button>
                      </Upload>
                    </div>
                    <div className={styles.examples}>
                      {
                        examples.map((item,index) => {
                          return (
                            <div className={styles.exampleItem} style={{background:item}} key={index} onClick={() => this.setState({currentCheck:item})}>
                              {
                                item == currentCheck ? <Icon type="check-circle" /> : ''
                              }
                            </div>
                          )
                        })
                      }
                    </div>
                    {
                      imgUrl ? <div className={styles.exampleImg} style={{
                        backgroundImage:`url(${imgUrl})`,backgroundRepeat:"no-repeat",backgroundSize:"100% 100%"}}
                        onClick={() => this.setState({currentCheck:imgUrl})}
                        >
                      {
                        imgUrl == currentCheck ? <Icon type="check-circle" /> : ''
                      }
                      </div> : ''
                    }
                    
                  </div>
                </div>
              </Form.Item>
            </Form>
            <Button type="primary" style={{marginTop:24}} onClick={this.doSave} disabled={isAdmin}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.save' })}</Button>
          </Tabs.TabPane>

          {
            isAdmin ? '' : (
              <Tabs.TabPane key="member" tab={formatMessage({ id: 'knowledgeFile.docLibrarySetting.permission' })}>
                <div className={styles.cardBox}>
                  <div style={{marginBottom:10}}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.publicScope' })}</div>
                  <Radio.Group value={info.permissionType} onChange={e => this.doSaveMember(e)}>
                    <Radio value={0} style={radioStyle}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.privacy' })}</Radio>
                    <Radio value={1} style={radioStyle}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.public' })}</Radio>
                  </Radio.Group>
                </div>
                
                <div style={{marginTop:24,width:"70%",display:"none"}}>
                  <div style={{marginBottom:10}}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.rolePermission' })}</div>
                  <Tabs 
                    activeKey={authType} 
                    onChange={this.onChangeAuthType} 
                    tabBarExtraContent={
                      <Input 
                        value={search} 
                        onChange={e => this.setState({search:e.target.value})} 
                        onPressEnter={this.doSearchByDocument} 
                        placeholder={formatMessage({ id: 'knowledgeFile.docLibrarySetting.searchMembers' })}
                        prefix={<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" data-icon="SearchOutlined"><path d="M16.473 17.887A9.46 9.46 0 0 1 10.5 20a9.5 9.5 0 1 1 9.5-9.5 9.46 9.46 0 0 1-2.113 5.973l3.773 3.773a.996.996 0 0 1-.007 1.407.996.996 0 0 1-1.407.007l-3.773-3.773ZM18 10.5a7.5 7.5 0 1 0-15 0 7.5 7.5 0 0 0 15 0Z" fill="currentColor"></path></svg>}
                      />}>
                    <Tabs.TabPane tab={formatMessage({ id: 'knowledgeFile.docLibrarySetting.admin' })} key={'0'}></Tabs.TabPane>
                    <Tabs.TabPane tab={formatMessage({ id: 'knowledgeFile.docLibrarySetting.editableMember' })} key={'1'}></Tabs.TabPane>
                    <Tabs.TabPane tab={formatMessage({ id: 'knowledgeFile.docLibrarySetting.viewableMember' })} key={'2'}></Tabs.TabPane>
                  </Tabs>
                  <AuthUserList onRef={ref => this.AuthUser = ref} pageSource="document" targetId={docLibraryId} authType={authType} />
                </div>
                
              </Tabs.TabPane>
            )
          }

          

          {
            /**
             * <Tabs.TabPane key="safety" tab="安全设置">
            <div className={styles.cardBox}>
              <div style={{marginBottom:10}}>是否允许文档库分享给应用？</div>
              <Radio.Group value={info.shareApplication} onChange={e => this.doSaveSafty(e.target.value,'shareApplication')}>
                <Radio value={0} style={radioStyle}>允许</Radio>
                <Radio value={1} style={radioStyle}>不允许</Radio>
              </Radio.Group>
            </div>

            <div className={styles.cardBox}>
              <div style={{marginBottom:10}}>谁可以移动或删除文档库的分类？</div>
              <Radio.Group value={info.operateSetting} onChange={e => this.doSaveSafty(e.target.value,'operateSetting')}>
                <Radio value={0} style={radioStyle}>管理员</Radio>
                <Radio value={1} style={radioStyle}>管理员与可编辑成员</Radio>
              </Radio.Group>
            </div>

            <div className={styles.cardBox}>
              <div style={{marginBottom:10}}>是否允许可编辑的用户对文档库内的页面内容进行导出？</div>
              <Radio.Group value={info.exportSetting} onChange={e => this.doSaveSafty(e.target.value,'exportSetting')}>
                <Radio value={0} style={radioStyle}>允许</Radio>
                <Radio value={1} style={radioStyle}>不允许</Radio>
              </Radio.Group>
            </div>
          </Tabs.TabPane>
             */
          }

          {
            isAdmin ? '' : (
              <Tabs.TabPane key="more" tab={formatMessage({ id: 'knowledgeFile.docLibrarySetting.more' })}>
                <div className={styles.cardBox}>
                  <div className={styles.messageBox}>
                    <Icon type="info-circle" /><span>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.deleteWarning' })}</span>
                  </div>

                  <Button type="danger" onClick={this.doDeleteConfirm}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.deleteButton' })}</Button>
                </div>
              </Tabs.TabPane>
            )
          }

          {
            isAdmin ? (
              <Tabs.TabPane key="authorized" tab={formatMessage({ id: 'knowledgeFile.docLibrarySetting.authorizedParties' })}>
                <div className={styles.cardBox}>
                  <b>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.publicDocLibrary' })}</b>
                  <div style={{margin:"10px 0 5px 0"}}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.authorizedDesc1' })}</div>
                  <div style={{marginBottom:5}}>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.authorizedDesc2' })}</div>
                  <div>{formatMessage({ id: 'knowledgeFile.docLibrarySetting.authorizedDesc3' })}</div>
                </div>

                <div style={{marginTop:24,width:"70%"}}>
                  <TenantUserList onRef={ref => this.TenantUserList = ref} targetId={docLibraryId} />
                </div>
              </Tabs.TabPane>
            ) : ''
          }
        </Tabs>

        
      </Card>
    )
  }
}

export default Form.create()(DocLibrarySetting)